import { useContext, useEffect, useState } from 'react';
import { Button, Modal, Space, message } from 'antd';
import { useUpdate } from '@/hooks/utils-hook';
import ModalContext from './ModalContext';
import useModal from './useModal';
import type { PropsWithChildren } from 'react';
import type { IProps } from './type';

const ModalPro = <TParams extends any[], DataType>(
	props: PropsWithChildren<IProps<TParams, DataType>>
) => {
	const { content, extendBtns, request, fetchRequest, onSuccess, onError } = props;
	const contextValue = useContext(ModalContext);
	const { store, setUpdateFunc, setModal } = contextValue;
	const [subLoading, setSubLoading] = useState(false);

	const update = useUpdate();

	useEffect(() => {
		setUpdateFunc(update);
	}, []);

	return (
		<Modal
			{...props}
			open={store.open}
			title={store.title}
			onCancel={() => setModal(false)}
			footer={
				<>
					{extendBtns}
					<Space style={{ marginLeft: '8px' }}>
						<Button type="primary" ghost onClick={() => setModal(false)}>
							取消
						</Button>
						<Button
							type="primary"
							loading={subLoading}
							onClick={async () => {
								try {
									setSubLoading(true);
									const result = await request(...fetchRequest()).finally(() =>
										setSubLoading(false)
									);
									onSuccess?.(result);
									setModal(false);
								} catch (error) {
									message.error('请求失败！');
									onError?.();
								}
							}}
						>
							确认
						</Button>
					</Space>
				</>
			}
		>
			{content}
		</Modal>
	);
};

const App = <TParams extends any[], RecordType>(props: IProps<TParams, RecordType>) => {
	const { modal } = props;

	const [modalRef] = useModal<RecordType>(modal);

	return (
		<ModalContext.Provider value={modalRef}>
			<ModalPro<TParams, RecordType> {...props} />
		</ModalContext.Provider>
	);
};

export default App;
